package com.credit.web.ec;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.credit.context.CreditServletContext;
import com.credit.entity.CreditUserInfo;
import com.credit.exception.ErrorException;
import com.credit.service.RedisService;
import com.credit.service.UserService;
import com.credit.util.Constants;
import com.credit.web.basic.bean.ResBean;

import net.sf.json.JSONObject;

@Component
public class GloableInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private RedisService redisService;
	@Autowired
	private UserService userService;
	
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		try{

			String appName = request.getHeader("appName");
			if(!StringUtils.isEmpty(appName)&&"xmdk".equals(appName)){
				String uri = request.getRequestURI();
				if(uri.indexOf("/product/list")>-1){
					return true;
				}
			}
			
			String token= request.getHeader("token");
	        
			if(StringUtils.isEmpty(token)){
	            throw new ErrorException(Constants.TOKEN_NOTNULL_ERROR_CODE, Constants.TOKEN_NOTNULL_ERROR_DESC);
			}
			
			CreditServletContext.setToken(token);
			
			Object idObject = redisService.getValue(token);
			
			if(idObject == null){
	            throw new ErrorException(Constants.TOKEN_NOTEXISTS_ERROR_CODE, Constants.TOKEN_NOTEXISTS_ERROR_DESC);
			}
			
			long userId = Long.valueOf(String.valueOf(idObject));
			
			CreditUserInfo userInfo = userService.findUserById(userId);
			
	        if(userInfo == null){
	            throw new ErrorException(Constants.TOKEN_NOTEXISTS_ERROR_CODE, Constants.TOKEN_NOTEXISTS_ERROR_DESC);
	        }
	        
	        CreditServletContext.setUserInfo(userInfo);
	        return true;
		}catch(ErrorException e){
			e.printStackTrace();
			ResBean resBean = new ResBean();
			resBean.setCode(e.getCode());
			resBean.setDesc(e.getMessage());
			
			response.getWriter().write(JSONObject.fromObject(resBean).toString());
			response.getWriter().flush();
			response.getWriter().close();
			
		}catch(Exception e){
			e.printStackTrace();
			ResBean resBean = new ResBean();
			resBean.setCode(Constants.SERVER_OTHER_ERROR_CODE);
			resBean.setDesc(Constants.SERVER_OTHER_ERROR_DESC);
			
			response.getWriter().write(JSONObject.fromObject(resBean).toString());
			response.getWriter().flush();
			response.getWriter().close();
			
		}       
		return false;
	}

}
